package com.example.mybatis_demo.config;

import com.example.mybatis_demo.datasource.DataSourceConstants;
import com.example.mybatis_demo.datasource.DynamicDatasource;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

//@Configuration
//@PropertySource("classpath:jdbc.properties")
public class DatasourceConfig {

    @ConfigurationProperties("spring.datasource.test01")
    public DataSource dataSource01() {
        return DataSourceBuilder.create().build();
    }

    @ConfigurationProperties("spring.datasource.test02")
    public DataSource dataSource02() {

        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dynamicDatasource() {

        final Map<Object, Object> datasourceMap = new HashMap<>();
        datasourceMap.put(DataSourceConstants.DATASOURCE_01, dataSource01());
        datasourceMap.put(DataSourceConstants.DATASOURCE_02, dataSource02());
        final DynamicDatasource dynamicDatasource = new DynamicDatasource();
        dynamicDatasource.setTargetDataSources(datasourceMap);
        dynamicDatasource.setDefaultTargetDataSource(dataSource01());
        return dynamicDatasource;
    }
}
